package com.aos.erp.schools.rest.student;


import com.aos.erp.common.GlobalConstant;
import com.aos.erp.common.bean.PageBean;
import com.aos.erp.common.bean.ResultEntity;
import com.aos.erp.common.exception.BizException;
import com.aos.erp.common.utils.DateUtils;
import com.aos.erp.schools.cutils.TimeUtils;
import com.aos.erp.schools.cutils.router.Rest;
import com.aos.erp.schools.model.gatherschool.entity.GatherSchool;
import com.aos.erp.schools.model.student.Student;
import com.aos.erp.schools.model.student.ro.student.AddStudentRo;
import com.aos.erp.schools.model.student.ro.student.SelectStudentRo;
import com.aos.erp.schools.model.student.ro.student.SelectSubmit122Ro;
import com.aos.erp.schools.model.student.ro.student.UpdateStudentRo;
import com.aos.erp.schools.model.student.vo.student.StudentAllVo;
import com.aos.erp.schools.model.student.vo.student.StudentBaseDataVo;
import com.aos.erp.schools.model.student.vo.student.StudentEaxmVo;
import com.aos.erp.schools.service.common.DictService;
import com.aos.erp.schools.service.gatherschool.GatherSchoolService;
import com.aos.erp.schools.service.student.StudentService;
import com.aos.erp.schools.util.ExcelData;
import com.aos.erp.schools.util.ExcelUtil;
import com.aos.erp.schools.util.UserUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Authorization;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 学员信息表 前端控制器
 * </p>
 *
 * @author chb
 * @since 2018-10-31
 */
@RestController
@RequestMapping(Rest.Student.ROOT)
@Api(tags = {"学员管理"})
public class StudentController {

    @Autowired
    private StudentService studentService ;
    @Resource
    private DictService dictService;
    @Resource
    private GatherSchoolService gatherSchoolService;

    @PostMapping(Rest.Student.add)
    @ApiOperation(value = "学员信息添加")
    public ResultEntity addUser(@Valid  AddStudentRo studentRo, BindingResult bindingResult){
        try {
                //用户id
                if (StringUtils.isEmpty(studentRo.getCurrentUserId())) {
                    return ResultEntity.failed("请重新登录", ResultEntity.CODE_NULL);
                }
                //数据 验证信息
                if (bindingResult.hasErrors()) {
                    return  ResultEntity.failed(bindingResult.getFieldErrors().get(0).getDefaultMessage());
                }
            GatherSchool driversSchoolId= UserUtil.getUserSchool(studentRo.getCurrentUserId());

            //（1：直营总校  2：非直营总校  3:分校 4：报名点）
            studentRo.setDriversId(driversSchoolId.getId());  //驾校id
            studentRo.setDriversSchoolType(driversSchoolId.getType());//驾校类型
               // 驾校
                if(driversSchoolId==null){
                    return ResultEntity.failed("驾校为空！不能进行添加操作", ResultEntity.CODE_NULL);
                }

                studentService.saveStudent(studentRo);
                return ResultEntity.success("学员添加成功!");

            }catch (BizException e) {
                return ResultEntity.failed(e.getMessage());
            }
            catch (Exception e) {
                e.printStackTrace();
                return ResultEntity.failed("学员信息添加失败!");
            }
    }

    @PostMapping(Rest.Student.update)
    @ApiOperation(value = "学员信息修改")
    public ResultEntity updateUser(@RequestBody UpdateStudentRo ro){
        try {
            //用户id
            if (StringUtils.isEmpty(ro.getCurrentUserId())) {
                return ResultEntity.failed("请重新登录", ResultEntity.CODE_NULL);
            }
            GatherSchool driversSchool= UserUtil.getUserSchool(ro.getCurrentUserId());
            ro.setDriversId(driversSchool.getId());  //驾校id
            ro.setDriversSchoolType(driversSchool.getType());//驾校类型

            studentService.updateStudent(ro);
            return ResultEntity.success("学员修改成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed("学员修改失败!");
        }
    }

    @GetMapping(Rest.Student.getStudentById)
    @ApiOperation(value = "单个学员信息查询", authorizations = @Authorization("TOKEN"))
    public ResultEntity<StudentAllVo> getStudentById(@RequestParam(value = "studentId")Long studentId){
        try {
            StudentAllVo student=studentService.queryObject(studentId);
            return ResultEntity.success(student);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed("学员信息查询失败!");
        }
    }

    @GetMapping(Rest.Student.getStudentAll)
    @ApiOperation(value = "学员所有信息查询")
    public ResultEntity<PageBean<StudentAllVo>> getStudentAll(SelectStudentRo ro) throws  Exception{

        //用户  驾校机构查询 没有做
        //用户id
        if (StringUtils.isEmpty(ro.getCurrentUserId())) {
            return ResultEntity.failed("请重新登录", ResultEntity.CODE_NULL);
        }
        GatherSchool driversSchool= UserUtil.getUserSchool(ro.getCurrentUserId());
        ro.setDriverId(driversSchool.getId());

        ro.setTimeStartName(TimeUtils.start(ro.getTimeStart()));
        ro.setTimeEddName(TimeUtils.edd(ro.getTimeEdd()));
        try {
            PageBean<StudentAllVo> student=studentService.queryByPage(ro);
            return ResultEntity.success(student);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed("学员信息查询失败!");
        }
    }

    @GetMapping(Rest.Student.del)
    @ApiOperation(value = "学员删除")
    public ResultEntity delStudent(@RequestParam(value = "ids[]")Long[]  ids){

             int num= studentService.deleteStudent(ids);
             if(num>0)
             {
                 return ResultEntity.success("学员删除成功!");
             }
            return ResultEntity.failed("学员删除失败!");

    }

    @ApiOperation(value = "学员添加页面基础数据", notes = "学员添加页面基础数据")
    @GetMapping(Rest.Student.getBaseData)
    public ResultEntity<StudentBaseDataVo> initBaseData( @RequestParam(name = "currentUserId", required = false) String currentUserId) throws Exception {

        if (StringUtils.isEmpty(currentUserId)) {
            return ResultEntity.failed("请重新登录", ResultEntity.CODE_NULL);
        }
        GatherSchool driversSchool= UserUtil.getUserSchool(currentUserId);
        if(driversSchool==null){
            return ResultEntity.failed("驾校id数据不存在");
        }
        StudentBaseDataVo baseDataVo = new StudentBaseDataVo();
        baseDataVo.setZjTypeList(dictService.findByParams("certificates"));
        baseDataVo.setCarTypeList(dictService.findByParams("car"));
        //TODO  这个几个数据字典 没有 数据 后期加上
        baseDataVo.setXzAddressTimeList(dictService.findByParams("car"));
        baseDataVo.setQuyuAddressList(dictService.findByParams("car"));
      baseDataVo.setDriverName(gatherSchoolService.querySchoolByUserId(currentUserId).getName());
        baseDataVo.setStudentNumber((int)(Math.random()*100)+"");
        return ResultEntity.success(baseDataVo);


    }

    @GetMapping(Rest.Student.getStateStudentNum)
    @ApiOperation(value = "查询需要提交122的学员数量")
    public ResultEntity getStateStudentNum(@RequestParam(name = "currentUserId", required = false) String currentUserId)throws Exception {

        if (StringUtils.isEmpty(currentUserId)) {
            return ResultEntity.failed("请重新登录", ResultEntity.CODE_NULL);
         }
        GatherSchool driversSchool= UserUtil.getUserSchool(currentUserId);
        if(driversSchool==null){
            return ResultEntity.failed("驾校数据不存在");
        }
        try {
             Integer  countStudent=studentService.getStateStudentNum(driversSchool.getId());
            return ResultEntity.success(countStudent);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed("查询失败!");
        }
    }

    @GetMapping(Rest.Student.sumbit122)
    @ApiOperation(value = "查询需要提交122的学员")
    public ResultEntity<PageBean<StudentAllVo>> sumbit122(SelectSubmit122Ro ro){

        try {
            if (StringUtils.isEmpty(ro.getCurrentUserId())) {
                return ResultEntity.failed("请重新登录", ResultEntity.CODE_NULL);
            }
            GatherSchool driversSchool= UserUtil.getUserSchool(ro.getCurrentUserId());
            if(driversSchool==null){
                return ResultEntity.failed("驾校数据不存在");
            }
            if(StringUtils.isEmpty(ro.getDriversName()))
            {
                ro.setDriversId(driversSchool.getId());
            }else{
                ro.setDriversId(Long.parseLong(ro.getDriversName()));
            }

            PageBean<StudentAllVo> student=studentService.queryListBy122(ro);

            return ResultEntity.success(student);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed("查询需要提交122!");
        }
    }

    @GetMapping(Rest.Student.updateState122State)
    @ApiOperation(value = "提交122的学员")
    public ResultEntity updateState122State(@RequestParam(value = "ids[]") Long[]  ids){

        //mq传递   给122
        int num= studentService.updateNetStatus(ids);
        if(num>0)
        {
            return ResultEntity.success("学员提交成功!");
        }
        return ResultEntity.failed("学员提交失败!");
    }


    //导出学员
    @GetMapping(GlobalConstant.GATEWAY_IGNORE+Rest.Student.export)
    public void exportData(HttpServletResponse response,@RequestParam(name = "currentUserId", required = false) String currentUserId,@RequestParam(value = "ids") String   ids) throws Exception {

       // GatherSchool driversSchool= UserUtil.getUserSchool(currentUserId);
        //      //  if(driversSchool!=null){
            String[]idsStr=ids.split(",");
            Long[] longAry= new Long[idsStr.length];
            for(int i = 0, len = idsStr.length; i < len; i++){
                longAry[i] = new Long(idsStr[i]);
            }

        // 获取导出数据
            List<StudentAllVo> studentInfoList = studentService.excelStudentExport(longAry);
            ExcelData excelData = getExcelData(studentInfoList);
            ExcelUtil.exportExcel(response,excelData);


    }

    /**
     * 封装导出数据
     * @param studentInfoList
     * @return
     */
    private ExcelData getExcelData( List<StudentAllVo> studentInfoList) {
        ExcelData excelData = new ExcelData();
        excelData.setFileName(DateUtils.getXXTimeString() + ".xls");
        String[] headArr = {"序号","姓名","证件号码","申请车型","登记住所","联系住所","联系电话","备注（是否通过审核）"};
        excelData.setHead(headArr);
        List<String[]> dataList = new ArrayList<>();
        for (StudentAllVo studentItem : studentInfoList) {
            String[] dataArr = new String[headArr.length];
            dataArr[0] = studentItem.getId()+"";
            dataArr[1] = studentItem.getName();
            dataArr[2] = studentItem.getCertificatesNumber();
            dataArr[3] = studentItem.getCarName();
            dataArr[4] = studentItem.getRegisteredResidence();
            dataArr[5] = studentItem.getAddressDetailed();
            dataArr[6] = studentItem.getPhone();
            dataArr[7] = studentItem.getInnerStatusName();
            dataList.add(dataArr);
        }
        excelData.setData(dataList);
        return excelData;
    }


}

